<template>
  <div class="member-search" :style="{ width: width + 'px', borderColor: BGcolor}" v-click-outside="handleClickOutside">
    <i class="icon-search"></i>
    <input type="text" v-model="searchTxt" class="input" :placeholder="placeholder" @focus="handleFocused" />
    <vc-svg v-show="searchTxt" class="icon-clear" name="clear" size="14" color="#8b8c8c" @click="hanldleClear"></vc-svg>
    <Transition name="searchResult">
      <div v-show="isFocused" v-spin="loading" class="search-result" @scroll.passive="handleScroll">
        <template v-if="searchTxt.length === 0">
          <div class="search-history">
            <div class="title">
              最近搜索
              <i class="icon-delete" title="清空" @click="removeSearchHistory" />
            </div>
            <div v-for="history in historyList" :key="history.id" class="history-item">
              <span class="item-name" @click="handleResultClick(history)">{{ history.name }}</span>
              <span v-if="memberIds.includes(history.id)" class="item-monitored">已监控</span>
              <span v-else class="item-monitor" @click="addMemberToGroup(history)">
                <span class="icon-add">+</span>
                <span>监控</span>
              </span>
            </div>
          </div>
        </template>
        <template v-else>
          <template v-if="resultList.length > 0">
            <div v-for="result in resultList" :key="result.id" class="result-item">
              <span v-html="result.name" class="item-name" @click="handleResultClick(result)"></span>
              <span v-if="memberIds.includes(result.id)" class="item-monitored">已监控</span>
              <span v-else class="item-monitor" @click="addMemberToGroup(result)">
                <span class="icon-add">+</span>
                <span>监控</span>
              </span>
            </div>
          </template>
          <template v-else>
            <vc-nodata :type="202"></vc-nodata>
          </template>
        </template>
      </div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
import { type SerachItem, type SearchParams, searchMember, addMember } from '../apis';
import { toF9 } from '@/utils';

interface Props {
  modelValue: string;
  memberIds: any[];
  groupId: number;
  width?: number;
  placeholder?: string;
}
const { modelValue, memberIds, groupId, width = 300, placeholder = '请输入企业名称关键字' } = defineProps<Props>();

const emit = defineEmits(['update:modelValue', 'refresh']);

const searchTxt = computed({
  get() {
    return modelValue;
  },
  set(value) {
    emit('update:modelValue', value);
  }
});

const isFocused = ref(false);
const BGcolor = ref('#E3E3E3')
const handleFocused = () => {
  isFocused.value = true;
  BGcolor.value='#02C680';
};
const hanldleClear = () => {
  searchTxt.value = '';
};
const handleClickOutside = () => {
  isFocused.value = false;
  BGcolor.value='#E3E3E3';
};

const HISTORY_KEY = 'VC_GROUP_MEMBER_SEARCH';
const historyList = ref<SerachItem[]>([]);
const getHistory = () => {
  const data = localStorage.getItem(HISTORY_KEY);
  historyList.value = data ? JSON.parse(data) : [];
};
getHistory();
const setHistory = (item: SerachItem) => {
  const i = historyList.value.findIndex((s: any) => s.id === item.id);
  if (historyList.value.length === 20) {
    if (i > -1) historyList.value.splice(i, 1);
    else historyList.value.pop();
  } else {
    if (i > -1) historyList.value.splice(i, 1);
  }
  historyList.value.unshift({
    id: item.id,
    /** 去除所有em标签 */
    name: item.name.replaceAll(/<[^>]+>/g, '')
  });
  localStorage.setItem(HISTORY_KEY, JSON.stringify(historyList.value));
};
const searchParams = reactive<SearchParams>({
  wd: '',
  limit: 20,
  offset: 0
});
const initSearch = (val: string) => {
  searchParams.wd = val;
  searchParams.offset = 0;
  resultList.value = [];
  getSearchResultList();
};
const loading = ref(false);
const hasMore = ref(true);
const resultList = ref<SerachItem[]>([]);
const getSearchResultList = async () => {
  try {
    loading.value = true;
    const res = await searchMember(searchParams);
    resultList.value = [...resultList.value, ...res.items];
    searchParams.offset += res.items.length;
    loading.value = false;
    if (res.items.length < searchParams.limit) {
      hasMore.value = false;
    }
  } catch {
    loading.value = false;
    resultList.value = [];
  }
};
const handleScroll = (e: Event) => {
  if (searchTxt.value.length && resultList.value.length) {
    const { clientHeight, scrollTop, scrollHeight } = e.target as HTMLElement;
    if (clientHeight + scrollTop >= scrollHeight - 30 && !loading.value && hasMore.value) {
      getSearchResultList();
    }
  }
};

const removeSearchHistory = () => {
  localStorage.removeItem(HISTORY_KEY);
  historyList.value = [];
};

const handleResultClick = (item: SerachItem) => {
  setHistory(item);
  nextTick(() => {
    toF9(item.id);
  });
};

const addMemberToGroup = async (item: SerachItem) => {
  const res = await addMember(groupId, [item.id]);
  if (res.code === 200) {
    setHistory(item);
    emit('refresh');
  }
};

const timer = ref();
watch(
  () => searchTxt.value,
  (val) => {
    if (val) {
      /** 搜索节流 */
      if (timer.value) clearTimeout(timer.value);
      loading.value = true;
      timer.value = setTimeout(() => initSearch(val), 500);
    } else {
      getHistory();
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped></style>

<style lang="scss">
.member-search {
  position: relative;
  padding: 0 12px;
  display: flex;
  align-items: center;
  height: 32px;
  border: 1px solid #E3E3E3;
  border-radius: 4px;
  .icon-search {
    flex-shrink: 0;
    margin-right: 12px;
    display: inline-block;
    width: 11px;
    height: 12px;
    background-image: url('');
    background-size: 100% 100%;
    background-repeat: no-repeat;
  }
  .input {
    flex: 1;
    padding-right: 16px;
    font-size: 14px;
    color: #BFBFBF;
    font-weight: 400;
    border: none;
    outline: none;
  }
  .icon-clear {
    position: absolute;
    right: 12px;
    height: 14px;
    cursor: pointer;
  }

  .search-result {
    position: absolute;
    z-index: 999;
    top: 39px;
    left: 0;
    padding: 16px 20px;
    width: 560px;
    height: 368px;
    overflow-y: auto;
    @include scroll-bar(#c0c4cc, 4px);
    background: #fff;
    border: 1px solid #f3f3f3;
    box-shadow: 2px 4px 10px rgba(187, 187, 187, 0.3);
    .search-history {
      .title {
        padding-bottom: 16px;
        font-size: 14px;
        font-weight: 500;
        color: #333;
        .icon-delete {
          position: relative;
          top: 1px;
          margin-left: 4px;
          display: inline-block;
          width: 12px;
          height: 13px;
          cursor: pointer;
          background-image: url('@/assets/delete.png');
          background-size: 100% 100%;
          background-repeat: no-repeat;
        }
      }
    }
    .history-item,
    .result-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      &:not(:last-child) {
        margin-bottom: 10px;
        padding-bottom: 12px;
        border-bottom: 1px solid #f6f6f6;
      }
      em {
        font-style: normal;
        color: #ff5959;
      }
      .item-name {
        font-size: 18px;
        cursor: pointer;
      }
      .item-monitored {
        flex-shrink: 0;
        padding: 2px 7px;
        font-size: 14px;
        color: #999;
        border: 1px solid #e3e3e3;
        border-radius: 2px;
      }
      .item-monitor {
        flex-shrink: 0;
        padding: 2px 7px;
        font-size: 14px;
        color: #008ef4;
        border: 1px solid #008ef4;
        border-radius: 2px;
        cursor: pointer;
        .icon-add {
          margin-right: 4px;
        }
      }
    }
  }
}

.searchResult-enter-active {
  animation: heightExpand 0.2s ease-in-out;
}
.searchResult-leave-active {
  animation: heightCollapse 0.2s ease-in;
}

@keyframes heightExpand {
  from {
    height: 0;
  }
  to {
    height: 368px;
  }
}
@keyframes heightCollapse {
  from {
    height: 368px;
  }
  to {
    height: 0;
  }
}
</style>
